package com.hspedu.seckill.exception;

import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespBean exceptionHandler(Exception e){
        if (e instanceof GlobalException){
            return RespBean.error(((GlobalException) e).getRespBeanEnum());
        }else if (e instanceof BindException){//绑定异常
            BindException ex = (BindException)e;
            RespBean respBean = RespBean.error(RespBeanEnum.BING_ERROR);
            //取出绑定异常中的错误信息
            respBean.setMessage(" 参 数 校 验 异 常 ~ ： " + ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }

}
